package com.xt.myapplication;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.xt.pro.BleNFCBindInfo;
import com.xthh.XTBaseNFCActivity;
import com.xthh.XTCore;
import com.xthh.XTUI;
import com.xthh._ble.HH_BleCommunicator;
import com.xthh._enum.HH_EnumDeviceColorType;
import com.xthh._enum.HH_EnumErrorCode;
import com.xthh._enum.HH_EnumFileType;
import com.xthh._enum.HH_EnumNfcErrorCode;
import com.xthh._enum.pic_storage.HH_EnumPicStorage_BrushType;
import com.xthh._enum.pic_storage.HH_EnumPicStorage_PicIndex;
import com.xthh._function.HH_CharUtil;
import com.xthh._function.HH_DialogUtil;
import com.xthh._function.HH_Logging;
import com.xthh._function.HH_PicUtils;
import com.xthh._function.HH_Spinner;
import com.xthh._function.HH_SystemUtil;
import com.xthh._function.HH_TimeUtil;
import com.xthh._function.HH_ToastUtils;
import com.xthh._function.MyPopWindow3.HH_T_SpinnerRosInfo;
import com.xthh._function._ini.HH_INI;
import com.xthh._function._language.HH_LanguageUtil;
import com.xthh._msg.HH_MSG;
import com.xthh._struct.HH_T_BindDevice;
import com.xthh._struct.HH_T_RGB_TJ;
import com.xthh._struct.HH_T_SNInfo;
import com.xthh._struct.HH_T_ScanResult;
import com.xthh._struct.HH_T_SystemParams;
import com.xthh.picselect.HH_Activity_PicFileSelect;

import java.util.ArrayList;
import java.util.List;

public class PicDisplayActivity extends XTBaseNFCActivity implements View.OnClickListener {
    final String TAG = "PicDisplayActivity";
    Context context;


    public static HandlenRecvMessage handlenRecvMessage;
    HH_EnumDeviceColorType deviceColorType = HH_EnumDeviceColorType.BLACK_WHITE_RED_YELLOW_3;
    HH_T_SystemParams systemParams;

    private AdapterCurrentTaskLogInfo mAdapterCurrentTaskLogInfo;
    ListView list_log_info;

    ListView listview_pic;
    private AdapterCurrentTaskPicInfo mAdapterCurrentTaskPicInfo;


    Button button_select_pic;

    int deviceW = 528;
    int deviceH = 768;
    String mac = "";
    boolean bIsBrushing = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pic_display);

        context = this;

        mac = getIntent().getStringExtra("MAC");

        HH_LanguageUtil.SetCurrentActivityLanguage(context);



        handlenRecvMessage = new HandlenRecvMessage();


        button_select_pic = findViewById(R.id.button_select_pic);
        button_select_pic.setOnClickListener(this);


        list_log_info = findViewById(R.id.list_log_info);
        mAdapterCurrentTaskLogInfo = new AdapterCurrentTaskLogInfo(this);
        list_log_info.setAdapter(mAdapterCurrentTaskLogInfo);


        listview_pic = findViewById(R.id.listview_pic);
        mAdapterCurrentTaskPicInfo = new AdapterCurrentTaskPicInfo(this);
        listview_pic.setAdapter(mAdapterCurrentTaskPicInfo);
        mAdapterCurrentTaskPicInfo.setOnDeviceClickListener(new AdapterCurrentTaskPicInfo.OnDeviceClickListener() {
            @Override
            public void onBrush(BInfo td, int position) {
                if (bIsBrushing){
                    HH_DialogUtil.tipsDialog(PicDisplayActivity.this, "再在刷，在等等");
                    return;
                }
                new Thread(new Runnable() {
                    public void run() {
                        bIsBrushing = true;
                        try {

                            HH_SystemUtil.SendMessage(systemParams, 2013, String.format("正在刷%d", position), 0, 0);
                            HH_EnumErrorCode code = HH_BleCommunicator.BrushPic(systemParams,
                                    mac,
                                    XTCore.GetSendPicData(td.getBitmap(), deviceColorType),
                                    2,
                                    true,
                                    "",
                                    2,
                                    -1);

                            HH_SystemUtil.SendMessage(systemParams, 2013, String.format("%d=%s", code.toString()), 0, 0);

                        } catch (Exception e) {
                        }
                        bIsBrushing = false;
                    }
                }).start();



            }
        });



        systemParams = new HH_T_SystemParams(getApplication(), context, handlenRecvMessage);
        deviceColorType = HH_INI.getDeviceColor(systemParams, "DEVICE_COLOR");

    }




    private void LoadLocalPic(String src) {
        //  共76个
        Bitmap btSrc = HH_PicUtils.GetBitmapFormFile(src);
        if (btSrc != null) {
            if (btSrc.getWidth() != deviceW || btSrc.getHeight() != deviceH) {
                btSrc = HH_PicUtils.zoomImg2(btSrc, deviceW, deviceH, 255, 255, 255);

            }
            if (btSrc != null) {


                // 测试的图需要旋转
                btSrc = HH_PicUtils.rotateBitmap(btSrc, 270);

                List<Bitmap> listBitmap = new ArrayList<>();
                for (int i = 0; i <= 50; i++){
                    listBitmap.add(btSrc);
                }

                new Thread(new Runnable() {
                    public void run() {
                        try {
                            // 77个算法
                            for (int i = 0; i < listBitmap.size(); i++){
                                Bitmap bt0 = listBitmap.get(i);

                                //String tempPath1 = HH_SystemUtil.GetTempPath(systemParams,i, HH_EnumFileType.BMP);
                                //HH_PicUtils.BitmapSaveFile(bt0, tempPath1);
                                //Bitmap bt2 = HH_PicUtils.GetBitmapFormFile(tempPath1);
                                // 测试用
                                Bitmap bt = HH_PicUtils.PicAddIndex(bt0, i);

                                bt = XTCore.PicDither(bt, deviceColorType, i, 2);

                                if (bt != null)
                                    HH_SystemUtil.SendMessage(systemParams, 2012, bt, i, 0);

                            }
                        } catch (Exception e) {
                            HH_Logging.i(TAG, systemParams, "brush-end fail = %s", e.toString());
                            e.printStackTrace();
                        }
                    }
                }).start();



                /*String tempPath1 = HH_SystemUtil.GetTempPath(systemParams,10, HH_EnumFileType.BMP);
                String tempPath2 = HH_SystemUtil.GetTempPath(systemParams,11, HH_EnumFileType.BMP);
                String tempPath3 = HH_SystemUtil.GetTempPath(systemParams,12, HH_EnumFileType.BMP);
                HH_PicUtils.BitmapSaveFile(b1, tempPath1);
                HH_PicUtils.BitmapSaveFile(b1, tempPath2);
                HH_PicUtils.BitmapSaveFile(b1, tempPath3);*/

                /*listSendData1 = new ArrayList<>();
                listSendData2 = new ArrayList<>();
                listSendData3 = new ArrayList<>();
                listSendData1 = DitherAddToControl(0, tempPath1, imageview_pic_1);
                listSendData2 = DitherAddToControl(1, tempPath2, imageview_pic_2);
                listSendData3 = DitherAddToControl(2, tempPath3, imageview_pic_3);*/

                /*new Thread(new Runnable() {
                    public void run() {
                        try {
                            HH_EnumErrorCode code = XTCore.BrushPic(systemParams,
                                    testMac, listSendData1, nPageIntervalTime,
                                    true, strDeviceIdentity, 2000,
                                    epdParams);


                        } catch (Exception e) {
                            HH_Logging.i(TAG, systemParams, "brush-end fail = %s", e.toString());
                            e.printStackTrace();
                        }
                    }
                }).start();*/

                return;

            }
        }
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button_select_pic:{
                mAdapterCurrentTaskPicInfo.clearAll();
                mAdapterCurrentTaskPicInfo.notifyDataSetChanged();

                Intent intent = new Intent(this, HH_Activity_PicFileSelect.class);
                ArrayList<String> listExts = new ArrayList<String>();
                listExts.add("png");
                listExts.add("jpg");
                listExts.add("jpeg");
                listExts.add("bmp");
                intent.putStringArrayListExtra(HH_Activity_PicFileSelect.FIND_FILE_EXT, listExts);
                intent.putExtra(HH_Activity_PicFileSelect.GET_FOLDER_DETAILS_INFO, false);
                startActivityForResult(intent, HH_MSG.XT_FILE_SELECT_PIC);
                break;
            }


            /*case R.id.button_brushpic_1:{
                if (listSendData1== null || listSendData1.size() <= 0){
                    HH_ToastUtils.showToast(systemParams.getCtx(), "先选图");
                    break;
                }
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            HH_EnumErrorCode code = XTCore.BrushPic(systemParams,
                                    testMac, listSendData1, nPageIntervalTime,
                                    true, strDeviceIdentity, 2000,
                                    epdParams);


                        } catch (Exception e) {
                            HH_Logging.i(TAG, systemParams, "brush-end fail = %s", e.toString());
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
            }*/


            case R.id.imageview_pic_3:{

                break;
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
           if (requestCode == HH_MSG.XT_FILE_SELECT_PIC){
                if (data != null) {
                    String path = data.getStringExtra("IMPORT_PATH_FILE");


                    LoadLocalPic(path);
                }
           }
        }
    }

    // 监听各种状态
    public class HandlenRecvMessage extends Handler {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){

                case 2012:{
                    Bitmap bt = (Bitmap)msg.obj;
                    mAdapterCurrentTaskPicInfo.addTaskInfo(new BInfo(bt, msg.arg1));
                    mAdapterCurrentTaskPicInfo.notifyDataSetChanged();

                    if (mAdapterCurrentTaskPicInfo.getCount() > 0)
                        listview_pic.setSelection(mAdapterCurrentTaskPicInfo.getCount() - 1);
                    break;
                }

                case 2013:{
                    AddLogInfo((String)msg.obj);
                    break;
                }
                case XTCore.MSG_LOG:{
                    HH_EnumErrorCode errorCode = HH_EnumErrorCode.values()[msg.arg2];
                    switch (errorCode) {
                        case DATA_FAIL:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("数据错误");
                            break;
                        case BLE_CONNECT_FAIL:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("蓝牙连接失败");
                            break;
                        case BLE_CHARACTERISTIC_FAIL:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("特征获取失败");
                            break;
                        case CLEAR_CACHE_FAIL:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("发送清空缓存指令失败");
                            break;
                        case SCAN_FINISH:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("扫描完成");
                            break;
                        case BLE_BEGIN_CONNECT:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("蓝牙开始连接");
                            break;
                        case BLE_DISABLE:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("蓝牙没有打开");
                            break;
                        case BLE_BRUSH_BEGIN:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("刷图开始");
                            break;
                        case BLE_BRUSH_DATA_SEND:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("数据传输中");
                            break;
                        case BLE_NFC_CLOSE_BEGIN:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("NFC断电开始");
                            break;
                        case BLE_OTA_BEGIN:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("OTA开始");
                            break;
                        case SCAN_FAIL:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("扫描失败");
                            break;
                        case SCAN_BEGIN:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("扫描开始");
                            break;
                        case SCAN_INFO: {
                            HH_T_BindDevice tbd = (HH_T_BindDevice) msg.obj;
                            if (tbd != null)
                                mAdapterCurrentTaskLogInfo.addTaskInfo(tbd.getMacRes());
                            break;
                        }
                        case SUCCESS:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("成功");
                            break;
                        case FAIL:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("失败");
                            break;
                        case BLE_CONNECT_SUCCESS:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("蓝牙连接成功");
                            break;
                        case BLE_BRUSH_ING:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("正在刷图");
                            break;
                        case BLE_DISCONNECT:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("蓝牙已断开");
                            break;
                        case BLE_IDENTITY_ENCRYPTION_BEGIN:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("身份加密开始");
                            break;
                        case BLE_IDENTITY_ENCRYPTION_FAIL:
                            mAdapterCurrentTaskLogInfo.addTaskInfo("认证失败");
                            break;
                        case TIME_CONSUME_BLE_CONNECT:{
                            mAdapterCurrentTaskLogInfo.addTaskInfo(String.format("连接用时：%d", msg.arg1));
                            break;
                        }
                        case TIME_CONSUME_DATA_SEND:{
                            mAdapterCurrentTaskLogInfo.addTaskInfo(String.format("数据发送用时：%d", msg.arg1));
                            break;
                        }
                        case TIME_CONSUME_BRUSH:{
                            mAdapterCurrentTaskLogInfo.addTaskInfo(String.format("刷图用时：%d", msg.arg1));
                            break;
                        }
                        case OTHER_INFO:{
                            mAdapterCurrentTaskLogInfo.addTaskInfo((String)msg.obj);
                            break;
                        }
                    }


                    mAdapterCurrentTaskLogInfo.notifyDataSetChanged();
                    if (mAdapterCurrentTaskLogInfo.getCount() > 0)
                        list_log_info.setSelection(mAdapterCurrentTaskLogInfo.getCount() - 1);


                    break;
                }

            }
        }

    }


    private void AddLogInfo(String info){
        if (info != null && info.length() > 0){
            mAdapterCurrentTaskLogInfo.addTaskInfo(info);
            mAdapterCurrentTaskLogInfo.notifyDataSetChanged();
            if (mAdapterCurrentTaskLogInfo.getCount() > 0)
                list_log_info.setSelection(mAdapterCurrentTaskLogInfo.getCount() - 1);
        }
    }

}